package com.sinoglobal.sinostore.fragment;

import andbase.view.pullview.AbPullToRefreshView;
import andbase.view.pullview.AbPullToRefreshView.OnHeaderRefreshListener;
import android.annotation.SuppressLint;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebSettings.LayoutAlgorithm;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageButton;
import android.widget.TextView;

import com.lidroid.xutils.util.LogUtils;
import com.sinoglobal.sinostore.R;
import com.sinoglobal.sinostore.activity.FirstActivity;
import com.sinoglobal.sinostore.activity.GoodsDetailActivity;
import com.sinoglobal.sinostore.activity.GoodsListActivity;
import com.sinoglobal.sinostore.activity.SecondKillActivity;

public class ActionFragment extends AbstractFragment implements OnHeaderRefreshListener {
	String url = "http://192.168.10.11:2010/index.php/shop";
	private WebView wv;
	private ValueCallback<Uri> mUploadMessage;
	
	private View view;
	/**标题**/
	private TextView tvTitle;
	/**标题右测按钮**/
	private TextView tvRightBtn;
	/**左侧按钮**/
	private ImageButton shopTitleButLeft;
	
//	private AbPullToRefreshView pullWebview;
	
	private SwipeRefreshLayout swipeLayout;
	
	

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.shop_action_layout, null);
		initView(view);
		return view;
	}

	@SuppressLint("SetJavaScriptEnabled")
	private void initView(View view) {
		tvTitle = (TextView) view.findViewById(R.id.shop_title_text);
		tvTitle.setText("女性专区");
		tvRightBtn = (TextView)view.findViewById(R.id.shop_title_right_text);
		tvRightBtn.setText("进入商城");
		shopTitleButLeft = (ImageButton)view.findViewById(R.id.shop_title_but_left);
		shopTitleButLeft.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if(wv.canGoBack()){
					shopTitleButLeft.setVisibility(View.GONE);
					tvTitle.setText("女性专区");
					tvRightBtn.setVisibility(View.VISIBLE);
					wv.loadUrl(url);
				}
//				if(!wv.canGoBack()){
//					shopTitleButLeft.setVisibility(View.GONE);
//					tvTitle.setText("女性专区");
//					tvRightBtn.setVisibility(View.VISIBLE);
//				}
			}
		});
		tvRightBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				toActivity(FirstActivity.class, null);
			}
		});
		
		swipeLayout = (SwipeRefreshLayout)view.findViewById(R.id.pull_webview);
		swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {  
            
            @Override  
            public void onRefresh() {  
                //重新刷新页面  
                wv.loadUrl(wv.getUrl());  
            }  
        }); 
		
//		pullWebview = (AbPullToRefreshView)view.findViewById(R.id.pull_webview);
//		pullWebview.setLoadMoreEnable(false);
//		pullWebview.setOnHeaderRefreshListener(this);
		
		wv = (WebView) view.findViewById(R.id.wv_action);
		CookieSyncManager.createInstance(getActivity());
		CookieSyncManager.getInstance().startSync();
		CookieManager.getInstance().removeSessionCookie();
		wv.clearCache(true);
		wv.clearHistory();
		wv.loadDataWithBaseURL("example-app://example.co.uk/", "", null, "UTF-8", null);
		wv.loadUrl(url);
		wv.getSettings().setDefaultTextEncodingName("utf-8");// 避免中文乱码
		wv.setSelected(true);
		wv.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);  
        //触摸焦点起作用  
		wv.requestFocus(); 
		WebSettings webSetting = wv.getSettings();
		webSetting.setJavaScriptEnabled(true);
		webSetting.setDomStorageEnabled(true);
		webSetting.setAllowFileAccess(true);
		webSetting.setJavaScriptCanOpenWindowsAutomatically(true);
		webSetting.setNeedInitialFocus(false);
		webSetting.setSupportZoom(true);
		webSetting.setBuiltInZoomControls(true);
		webSetting.setUseWideViewPort(true);
		webSetting.setLoadWithOverviewMode(true);
		webSetting.setLayoutAlgorithm(LayoutAlgorithm.NORMAL);  
		webSetting.setDefaultFontSize(14);
		wv.setWebChromeClient(new WebChromeClient() {
			@Override  
            public void onReceivedTitle(WebView view, String title) {  
                super.onReceivedTitle(view, title);  
            }  
			// For Android 3.0+
			public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
				if (mUploadMessage != null)
					return;
				mUploadMessage = uploadMsg;
			}

			// For Android < 3.0
			@SuppressWarnings("unused")
			public void openFileChooser(ValueCallback<Uri> uploadMsg) {
				// showShortToastMessage("// For Android < 3.0");
				openFileChooser(uploadMsg, "");
			}

			// For Android > 4.1.1
			@SuppressWarnings("unused")
			public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
				openFileChooser(uploadMsg, acceptType);
				// showShortToastMessage("// For Android > 4.1.1");
			}

			public void onExceededDatabaseQuota(String url, String databaseIdentifier, long quota, long estimatedDatabaseSize,
					long totalQuota, android.webkit.WebStorage.QuotaUpdater quotaUpdater) {
				super.onExceededDatabaseQuota(url, databaseIdentifier, quota, estimatedDatabaseSize, totalQuota, quotaUpdater);
			};

			public void onReachedMaxAppCacheSize(long requiredStorage, long quota, android.webkit.WebStorage.QuotaUpdater quotaUpdater) {
				super.onReachedMaxAppCacheSize(requiredStorage, quota, quotaUpdater);
			};
			
			@Override
			public void onProgressChanged(WebView view, int newProgress) {
				 if (newProgress == 100) {  
	                    //隐藏进度条  
	                    swipeLayout.setRefreshing(false);  
	                } else {  
	                    if (!swipeLayout.isRefreshing())  
	                        swipeLayout.setRefreshing(true);  
	                }  
				super.onProgressChanged(view, newProgress);
			}

		});
		wv.setWebViewClient(new webviewClient());
	}

	// 系统的返回按钮的处理
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// 判断是否按下了系统的返回按钮以及webview的返回按钮
		if ((keyCode == KeyEvent.KEYCODE_BACK) && wv.canGoBack()) {
			wv.goBack(); // goBack()表示返回WebView的上一页面
			return true;
		}
		// 下边这个判断是返回到webview的第一页的时候系统的返回按钮，返回到app
		else if ((keyCode == KeyEvent.KEYCODE_BACK) && wv != null) {
			CookieSyncManager.createInstance(getActivity());
			CookieSyncManager.getInstance().startSync();
			CookieManager.getInstance().removeSessionCookie();
			wv.clearCache(true);
			wv.clearHistory();
			getActivity().finish();
		}
		return true;
	}

	private class webviewClient extends WebViewClient {

		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			LogUtils.i(">>>>>>>>>>>>>url:"+url);
			Uri uri = Uri.parse(url);
			int type = 0;
				try {
					type = Integer.parseInt(uri.getQueryParameter("type"));
				} catch (Exception e) {
				}
				String gid = uri.getQueryParameter("gid");
				String fid = uri.getQueryParameter("fid");
				String title = uri.getQueryParameter("title");
				switch (type) {//7=商城首页|8=商城分类|9=商品详情|10=商城活动
				case 7://商城首页
					toActivity(FirstActivity.class, null);
					break;
				case 8://商城分类
					Bundle bundle = new Bundle();
					bundle.putBoolean("fromHomePage", false);
					bundle.putString("typeId", gid);
					toActivity(GoodsListActivity.class, bundle);
					break;
				case 9://商品详情
					Bundle goodsDetail = new Bundle();
					goodsDetail.putString("goodsId", gid);
					toActivity(GoodsDetailActivity.class, goodsDetail);
					break;
				case 10://商城活动
					Bundle secondKill = new Bundle();
					secondKill.putString("id", fid);
					secondKill.putString("activityId", gid);
					toActivity(SecondKillActivity.class, secondKill);
					break;
				case 11://跳转web页面
					view.loadUrl(url);
					shopTitleButLeft.setVisibility(View.VISIBLE);
					tvTitle.setText(title);
					tvRightBtn.setVisibility(View.GONE);
					break;
				default:
					view.loadUrl(url);
					break;
				}
			return true;
		}

		@Override
		public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
			super.onReceivedError(view, errorCode, description, failingUrl);
		}

		@Override
		public void onPageFinished(WebView view, String url) {
			super.onPageFinished(view, url);
//			pullWebview.onHeaderRefreshFinish();
		}
	}

	@Override
	public void onHeaderRefresh(AbPullToRefreshView view) {
		wv.loadUrl(url);
	}


}
